package com.example.security.handle;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/5/29 19:46
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest req,HttpServletResponse res,AuthenticationException e) throws IOException, ServletException {

        ResponseMsg.response(res,map-> {
            map.put("code",HttpStatus.FAILED_DEPENDENCY.value());
            if (e instanceof LockedException) {
                map.put("msg","账户被锁定，登录失败!");
            } else if (e instanceof UsernameNotFoundException) {
                map.put("msg","用户名不存在!");
            } else if (e instanceof BadCredentialsException) {
                map.put("msg","用密码输入错误，登录失败!");
            } else if (e instanceof DisabledException) {
                map.put("msg","账户被禁用，登录失败!");
            } else if (e instanceof AccountExpiredException) {
                map.put("msg","账户过期，登录失败!");
            } else if (e instanceof CredentialsExpiredException) {
                map.put("msg","密码过期，登录失败!");
            } else {
                map.put("msg","登录失败!");
            }
        });

    }
}
